package com.linln.modules.system.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;

public class WeChatPayUtil {

    // 生成签名
    public static String generateSign(Map<String, String> params, String key) throws Exception {
        StringBuilder sb = new StringBuilder();
        params.entrySet().stream()
                .filter(entry -> entry.getValue() != null && !entry.getValue().isEmpty())
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
        sb.append("key=").append(key);
        return MD5(sb.toString()).toUpperCase(); // 使用 MD5 签名
    }

    // 将 Map 转换为 XML
    private static String toXml(Map<String, String> params) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");
        params.forEach((k, v) -> root.addElement(k).setText(v));
        return document.asXML();
    }

    // 发送 POST 请求
    private static String post(String url, String data) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(data, "UTF-8"));
        HttpResponse response = client.execute(post);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    // 解析 XML 返回值
    public static Map<String, String> parseXml(String xml) throws Exception {
        Map<String, String> result = new HashMap<>();
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        for (Element element : root.elements()) {
            result.put(element.getName(), element.getText());
        }
        return result;
    }

    // 解析微信回调的XML数据
    public static Map<String, String> parseXmls(HttpServletRequest request) throws IOException, DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(request.getInputStream());
        Element root = document.getRootElement();
        Map<String, String> map = new HashMap<>();
        for (Iterator<Element> it = root.elementIterator(); it.hasNext(); ) {
            Element e = it.next();
            map.put(e.getName(), e.getText());
        }
        return map;
    }

    // MD5 加密
    private static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
}
